package com.hmall.trade.listen;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constant.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class DelayListener {
    private final IOrderService orderService;
    private final PayClient payClient;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.DELAY_TRADE_QUEUE,durable = "true"),
            exchange = @Exchange(value = MQConstants.DELAY_TRADE_EXCHANGE,delayed = "true"),
            key = {MQConstants.DELAY_KEY}
    ))
    public void listenDelayQueue(Long id){
        //5.1查询订单表，看看是否已经完成交易
        Order order  = orderService.getById(id);
        if(order == null || order.getStatus().equals(2)){
            return;
        }
        //5.2没有完成，马上发网络请求给pay服务
        PayOrderDTO payOrderDTO = payClient.queryByBizOrderNo(id);
        if(payOrderDTO.getStatus() == 3){
            //成功了，更改状态
            orderService.markOrderPaySuccess(id);
        }else {
            //TODO 失败了，回退 库存，状态，购物车
            orderService.cancelOrder(id);
        }
    }
}
